package com.fenrirtec.aepp.common.api;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.fenrirtec.aepp.common.dto.TenderDetailDto;
import com.fenrirtec.aepp.common.dto.TenderMemberStatusDto;
import com.fenrirtec.aepp.common.service.TenderService;
import com.fenrirtec.aepp.common.service.impl.TenderServiceImpl;
import com.fenrirtec.aepp.common.support.JSONActionSupport;
import com.fenrirtec.core.definition.BaseDefinition.API;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.JsonUtils;

public class TenderDetailAPI extends JSONActionSupport {

	private static final long serialVersionUID = 1L;

	private static final Logger logger = LoggerFactory.getLogger(TenderDetailAPI.class);

	public TenderDetailAPI() {
	}
	
	private String param;

	public String getParam() {
		return this.param;
	}

	public void setParam(String param) {
		this.param = param;
	}

    @Override
	protected List<ErrorInfo> doValidate() {
		return null;
	}

	@Override
	protected JSONObject doExecute() {
		
		TenderService service = new TenderServiceImpl();
		TenderDetailDto tenderDetailDto = null;
		TenderMemberStatusDto tenderMemberStatusDto = null;
		
		try {
			JSONObject jsonObj = JSONObject.parseObject(this.param);
			Integer tenderId = jsonObj.getInteger("tender_id");
			tenderDetailDto = service.findDetail(tenderId);
			String memberLoginName = jsonObj.getString("member_login_name");
			if (StringUtils.isNotEmpty(memberLoginName)) {
			    tenderMemberStatusDto = service.findTenderMemberStatus(tenderId, memberLoginName);
			}
		} catch (DatabaseException e) {
			if (logger.isErrorEnabled()) {
				logger.error("database error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		} catch (UnexpectedException e) {
			if (logger.isErrorEnabled()) {
				logger.error("unexpected error occurred.", e);
			}
			throw new JSONActionStatusException(API.Common.Status.DB_ERROR, e);
		}
		
		JSONObject root = new JSONObject();
		JSONObject tender = new JSONObject();
		if (tenderDetailDto != null) {
    		if (tenderMemberStatusDto != null) {
    		    tender.putAll(JsonUtils.fromBean(tenderMemberStatusDto));
    		}
    		tender.putAll(JsonUtils.fromBean(tenderDetailDto));
		}
		root.put("tender", tender);
		return root;
	}

}
